package cn.iocoder.mall.user.application.controller.seller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.iocoder.common.utils.common.api.vo.Result;
import cn.iocoder.common.utils.common.system.query.QueryGenerator;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.util.UUIDGenerator;
import cn.iocoder.common.utils.common.util.json.JacksonUtils;
import cn.iocoder.common.utils.common.util.oConvertUtils;
import cn.iocoder.mall.shop.api.ShopService;
import cn.iocoder.mall.shop.api.pojo.ShopDTO;
import cn.iocoder.mall.user.api.entities.SellerCle;
import cn.iocoder.mall.user.biz.dataobject.Seller;
import cn.iocoder.mall.user.biz.service.ISellerService;
import cn.iocoder.mall.user.biz.untils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @Auther: LL
 * @Date: 2019/10/30 09:57
 */
@Slf4j
@Api(tags="商户操作店员的增删改查")
@RestController
@RequestMapping("/clerk")
public class ClerkController {
    @Autowired
    private ISellerService sellerService;
    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Reference(validation = "true", version = "${dubbo.consumer.ShopService.version}")
    ShopService shopService;

    /**
     * 分页列表查询
     * @param seller
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="店员的增删改查-分页列表查询", notes="店员的增删改查-分页列表查询")
    @GetMapping(value = "/merchant/list")
    public Result<IPage<Seller>> queryPageList(Seller seller,
                                               @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                               HttpServletRequest req) {
        Result<IPage<Seller>> result = new Result<IPage<Seller>>();
        QueryWrapper<Seller> queryWrapper = QueryGenerator.initQueryWrapper(seller, req.getParameterMap());
        Page<Seller> page = new Page<Seller>(pageNo, pageSize);
        IPage<Seller> pageList = sellerService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    /**
     *   添加
     * @param sellerCle
     * @return
     */
    @PostMapping(value = "/merchant/add")
    public Result<?> add(@Valid @RequestBody SellerCle sellerCle , BindingResult bindingResult) {
        Result<Seller> result = new Result<Seller>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        String code= (String) redisUtil.getSellerCode(sellerCle.getMobile());
        Seller seller=new Seller();
        BeanUtil.copyProperties(sellerCle,seller);
        String id= JwtUtil.getUserInfoByToken().getUserId();
        //查询该用户是否已添加过
        Seller dbSeller = sellerService.getOneUser(seller.getMobile());
        //设置店员id
        seller.setId(UUIDGenerator.generate());
        String clerkId=seller.getId();
        if(StringUtils.isNotBlank(code) && code.equals(sellerCle.getCode())){
            if(null!=dbSeller && dbSeller.getMobile().equals(sellerCle.getMobile())){
//                if (dbSeller.getType()==0){
                    return Result.error("该手机号已被注册");
//                }
//                dbSeller.setIsDelete(0);
//                sellerService.recoverOneUser(dbSeller.getId());
//          新增店员与店主的关系
//                sellerService.insertOneClerkRelationShip(id,dbSeller.getId());
            }else {
                try {
                    seller.setType(1);
                    seller.setNickName(RandomUtil.randomString(5));
                    seller.setCreateTime(new Date());
                    sellerService.save(seller);
                    sellerService.insertOneClerkRelationShip(id,clerkId);
                    result.success("添加成功！");
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                    result.error500("操作失败");
                }
            }
        }else {
            result.error500("验证码错误！");
        }
        return result;
    }
    /**
     *  编辑
     * @param seller
     * @return
     */
    @ApiOperation(value="商户编辑店员的增删改查-编辑", notes="店员的增删改查-编辑")
    @PostMapping(value = "/merchant/edit")
    public Result<Seller> edit(@Valid @RequestBody Seller seller,BindingResult bindingResult) {
        Result<Seller> result = new Result<Seller>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        Seller sellerEntity = sellerService.getById(seller.getId());
        if(sellerEntity==null) {
            result.error500("未找到对应实体");
        }else {
                boolean ok = sellerService.updateById(seller);
                //TODO 返回false说明什么？
                if(ok) {
                    result.success("修改成功!");
                }
            }
        return result;
    }

    /**
     *   通过id删除
     * @param sellerCle
     * @return
     */
    @ApiOperation(value="商户删除店员的增删改查-通过id删除", notes="店员的增删改查-通过id删除")
    @PostMapping(value = "/merchant/delete")
    public Result<?> delete(@RequestBody SellerCle sellerCle) {
        if(sellerCle==null||StringUtils.isBlank(sellerCle.getId())){
            return Result.error("参数错误,id为空");
        }
        String sellerId=JwtUtil.getUserInfoByToken().getUserId();
        try {
            sellerService.deleteOneById(sellerCle.getId());
            sellerService.deleteOneSellerClerk(sellerId,sellerCle.getId());
            shopService.deleteAllRelationShip(sellerCle.getId());
        } catch (Exception e) {
            log.error("删除失败",e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     *  批量删除
     * @param sellerCle
     * @return
     */
    @ApiOperation(value="商户批量删除店员的增删改查-批量删除", notes="店员的增删改查-批量删除")
    @PostMapping(value = "/merchant/deleteBatch")
    public Result<Seller> deleteBatch(@RequestBody SellerCle sellerCle) {
        Result<Seller> result = new Result<Seller>();
        if(sellerCle==null&&StringUtils.isBlank(sellerCle.getId())){
            return result.error500("参数错误,id为空");
        }
        String sellerId=JwtUtil.getUserInfoByToken().getUserId();
        if(sellerCle.getId()==null || "".equals(sellerCle.getId().trim())) {
            result.error500("参数不识别！");
        }else {
            this.sellerService.deleteListById(Arrays.asList(sellerCle.getId().split(",")));
            sellerService.deleteListSellerClerk(sellerId,Arrays.asList(sellerCle.getId().split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @ApiOperation(value="商户查询店员的增删改查-通过id查询", notes="店员的增删改查-通过id查询")
    @GetMapping(value = "/merchant/queryById")
    public Result<Seller> queryById(@RequestParam(name="id",required=true) String id) {
        Result<Seller> result = new Result<Seller>();
        if(StringUtils.isBlank(id)){
            return result.error500("参数错误,id为空");
        }
        Seller seller = sellerService.getById(id);
        if(seller==null) {
            result.error500("未找到对应实体");
        }else {
            result.setResult(seller);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/merchant/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<Seller> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                Seller seller = JSON.parseObject(deString, Seller.class);
                queryWrapper = QueryGenerator.initQueryWrapper(seller, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Seller> pageList = sellerService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "商户/店员列表");
        mv.addObject(NormalExcelConstants.CLASS, Seller.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商户/店员列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/merchant/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Seller> listSellers = ExcelImportUtil.importExcel(file.getInputStream(), Seller.class, params);
                sellerService.saveBatch(listSellers);
                return Result.ok("文件导入成功！数据行数:" + listSellers.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败:"+e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
    /**
     * 查询店员所属店铺列表
     * @param sellerId 店员ID
     * @return
     */
    @GetMapping("/merchant/queryClerkBelongShops")
    public Result<?> queryClerkBelongShops(@RequestParam(name="sellerId",required=true)String sellerId) {
        Result result = new Result();
        if(StringUtils.isBlank(sellerId)){
            return result.error500("参数错误,sellerId为空");
        }
        List<ShopDTO> shopDTOS = sellerService.queryClerkBelongShops(sellerId);
        return Result.ok(shopDTOS);
    }
}

